package com.warrantyhotel.android.ui;

import java.io.File;
import java.io.InputStream;
import java.util.Calendar;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Email;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.warrantyhotel.android.R;
import com.warrantyhotel.android.db.QueriesCodes;
import com.warrantyhotel.android.db.WarrantyHotelDBSchema.WarrantiesTable;
import com.warrantyhotel.android.model.Keys;
import com.warrantyhotel.android.service.UpdateIntentService;
import com.warrantyhotel.android.util.DateUtis;
import com.warrantyhotel.android.util.DetachableResultReceiver;
import com.warrantyhotel.android.util.DetachableResultReceiver.Receiver;
import com.warrantyhotel.android.util.MyPreferences;
import com.warrantyhotel.android.util.NotifyingAsyncQueryHandler;
import com.warrantyhotel.android.util.NotifyingAsyncQueryHandler.AsyncQueryListener;
import com.warrantyhotel.android.util.ToastUtil;
import com.warrantyhotel.android.util.imLoader2.ImageLoader;
import com.warrantyhotel.android.widget.TakeImageDialog;
import com.warrantyhotel.android.widget.TakeImageDialogWithImage;

public class UploadActivity extends Activity implements Receiver, AsyncQueryListener {

	// private static final String TAG = UploadActivity.class.getSimpleName();

	private Calendar calendar;
	private static final int DATE_DIALOG_ID_PURCHASE = 0;
	private static final int DATE_DIALOG_ID_EXPIRE = 1;
	private static final int SELECT_PHOTO = 100;
	private static final int IMAGE_PICKER_REQUEST = 101;
	// private static final int TRANSFER_DIALOG = 155;
	private static final int PICK_CONTACT = 156;
	private static final int CONFIRM = 28;
	private static final int CLOSE_ACTIVITY = 29;
	public static final String IMAGE_JPG = "image/jpeg";
	public static final String APPLICATION_PDF = "application/pdf";
	private EditText edtTranferEmail;

//	private Button currentButton;
	private ImageView imageToUpload;
	private Bitmap imageBitmap;
	private Button saveButton;

	private EditText productName;
	private EditText storeName;
	private EditText comments;

	private Button purchaseDate;
	private Button expiryDate;
	private TextView title;
	private NotifyingAsyncQueryHandler mHandler;
	// private final static String TEMP_FILE_IMAGE = "warranty_picture.jpeg";
	// private final static String TEMP_FILE_PDF = "warranty_pdf.pdf";
	private String accountUploadID = null;

	private boolean isImageUpload = false;
	private DetachableResultReceiver receiver;
	private ProgressDialog progress;
	private Uri mCapturedImageURI;
	// private String pathToImage;
	private File cacheDir;
	private boolean isSomeChanges;
	private String content_type = null;

	private String sProduct = "";
	private String sStore = "";
	private String sComment = "";
	private String uriGallery = null;
	private Bitmap initialBitmap;
	private boolean advancedPopup = false;
	private boolean needClaerCasce = false;
	private ImageLoader imLoader;
	private String uploadId = null;

	private BitmapFactory.Options _bitmapOptions;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.upload);

		imLoader = new ImageLoader(this);
		mHandler = new NotifyingAsyncQueryHandler(getContentResolver(), this);

		receiver = new DetachableResultReceiver(new Handler());
		receiver.setReceiver(this);
		isSomeChanges = false;

		title = (TextView) findViewById(R.id.uploadTitle);
		productName = (EditText) findViewById(R.id.product_name);
		storeName = (EditText) findViewById(R.id.store_name);
		comments = (EditText) findViewById(R.id.comments);
		purchaseDate = (Button) findViewById(R.id.data_purchase_button);
		expiryDate = (Button) findViewById(R.id.data_expiry_button);
		imageToUpload = (ImageView) findViewById(R.id.image_to_upload);
		saveButton = (Button) findViewById(R.id.upload_buton);
		saveButton.requestFocus();

		calendar = Calendar.getInstance();

		Bundle bundle = getIntent().getExtras();
		if (null != bundle && bundle.containsKey(Keys._warrantyId)) {
			uploadId = bundle.getString(Keys._warrantyId);
			retrieveWarrantyType(uploadId);
			title.setText(getString(R.string.update_warranty));
		}

		if (null != bundle && bundle.containsKey(Keys._advancedPopup)) {
			advancedPopup = true;
		}

		cacheDir = this.getCacheDir();
		if (!cacheDir.exists()) {
			cacheDir.mkdirs();
		}

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		if (uploadId != null)
			inflater.inflate(R.menu.menu_transfer_upload, menu);
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.transfer_upload:
			// showDialog(TRANSFER_DIALOG);

			Intent intent = new Intent(getApplicationContext(), TransferEmailActivity.class);
			intent.putExtra(Keys._account_upload_id, uploadId);
			startActivity(intent);
			return true;

		default:
			return super.onOptionsItemSelected(item);
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
	}

	@Override
	protected void onStop() {
		super.onStop();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (initialBitmap != null)
			initialBitmap.recycle();
		if (needClaerCasce)
			imLoader.clearCache();
	}

	private void retrieveWarrantyType(String id) {
		String[] projectionWarranty = { WarrantiesTable._ID, WarrantiesTable.FILE_NAME, WarrantiesTable.WARRANTY_ID, WarrantiesTable.PRODUCT_NAME_TO_UPLOAD,
				WarrantiesTable.STORE_NAME, WarrantiesTable.PURCHASE_DATE, WarrantiesTable.EXPIRATION_DATE, WarrantiesTable.FILE_NAME,
				WarrantiesTable.FILE_URL, WarrantiesTable.CONTENT_TYPE_WARRANTY, WarrantiesTable.THUMBNAIL_URL, WarrantiesTable.COMMENTS,
				WarrantiesTable.CONTENT_TYPE_WARRANTY, WarrantiesTable.IMAGE_URL };

		mHandler.startQuery(QueriesCodes.WARRANTY_BY_ACCOUNT_ID, WarrantiesTable.CONTENT_URI, projectionWarranty, WarrantiesTable.WARRANTY_ID + " = '" + id
				+ "'", null, null);
	}

	@Override
	public void onQueryComplete(int token, Object cookie, Cursor cursor) {
		switch (token) {
		case QueriesCodes.WARRANTY_BY_ACCOUNT_ID:
			if (cursor != null) {
				startManagingCursor(cursor);
				if (cursor.moveToFirst()) {
					// in that case warranty warranty id = account_upload_id

					sProduct = cursor.getString(cursor.getColumnIndex(WarrantiesTable.PRODUCT_NAME_TO_UPLOAD));
					sStore = cursor.getString(cursor.getColumnIndex(WarrantiesTable.STORE_NAME));
					sComment = cursor.getString(cursor.getColumnIndex(WarrantiesTable.COMMENTS));

					accountUploadID = cursor.getString(cursor.getColumnIndex(WarrantiesTable.WARRANTY_ID));

					storeName.setText(sStore);
					productName.setText(sProduct);
					comments.setText(sComment);

					String exp_date = cursor.getString(cursor.getColumnIndex(WarrantiesTable.EXPIRATION_DATE));
					long pur_date = cursor.getLong(cursor.getColumnIndex(WarrantiesTable.PURCHASE_DATE));

					Log.e(" ", exp_date + " " + pur_date);

					if (null != exp_date)
						expiryDate.setText(DateUtis.parseDate(exp_date));
					if (0 != pur_date)
						purchaseDate.setText(DateUtis.parseDateFromMilliseconds(pur_date));

					String file_url = cursor.getString(cursor.getColumnIndex(WarrantiesTable.FILE_URL));
					Log.e("FILE_URL", file_url);
					content_type = cursor.getString(cursor.getColumnIndex(WarrantiesTable.CONTENT_TYPE_WARRANTY));
					final String iamge_url = cursor.getString(cursor.getColumnIndex(WarrantiesTable.IMAGE_URL));
					Log.e("IMAGE_URL", iamge_url);

					// String temp_image_or_pdf = null;
					// TODO
					if (content_type != null && content_type.equals(APPLICATION_PDF)) {
						imLoader.DisplayImage(file_url, imageToUpload);
						// temp_image_or_pdf = TEMP_FILE_PDF;
						// new DownloadFilesTask().execute(new String[] {
						// TEMP_FILE_PDF, file_url });
						// imLoader.DisplayImage(file_url, imageToUpload);
						new Handler().postDelayed(new Runnable() {
							@Override
							public void run() {
								imageToUpload.setImageResource(R.drawable.pdf);
							}
						}, 1500);
					} else {
						// temp_image_or_pdf = TEMP_FILE_IMAGE;
						imLoader.DisplayImage(file_url, imageToUpload);
					}
				}
			}
			break;
		default:
			break;
		}
	}

	public void onUpload(View view) {
		if (TextUtils.isEmpty(productName.getText().toString().trim())) {
			ToastUtil.showText(getApplicationContext(), getString(R.string.product_name_is_empty));
		} else {
			doUpload();
		}
	}

	public void doUpload() {

		Intent uploadWarrantyIntent = new Intent(Intent.ACTION_SYNC, null, this, UpdateIntentService.class);

		if (null != accountUploadID) {
			uploadWarrantyIntent.putExtra(Keys._account_upload_id, accountUploadID);
		}
		uploadWarrantyIntent.putExtra(Keys._productName, productName.getText().toString().trim());
		uploadWarrantyIntent.putExtra(Keys._storeName, storeName.getText().toString().trim());
		uploadWarrantyIntent.putExtra(Keys._comments, comments.getText().toString().trim());
		if (isImageUpload) {
			if (uriGallery != null)
				uploadWarrantyIntent.putExtra(Keys._base64File_Gallery, uriGallery);
		}

		if (purchaseDate.getTag() != null) {
			long date = (Long) purchaseDate.getTag();
			uploadWarrantyIntent.putExtra(Keys._purchaseDate, DateUtis.decodeDate(date));
		}

		if (expiryDate.getTag() != null) {
			long date = (Long) expiryDate.getTag();
			uploadWarrantyIntent.putExtra(Keys._expirationDate, DateUtis.decodeDate(date));
		}
		progress = ProgressDialog.show(this, getString(R.string.loading), getString(R.string.please_wait), true, false);
		uploadWarrantyIntent.putExtra(UpdateIntentService.EXTRA_STATUS_RECEIVER, receiver);
		uploadWarrantyIntent.putExtra(UpdateIntentService.EXTRA_REQUEST_CODE, QueriesCodes.WARRANTY_UPLOAD);
		startService(uploadWarrantyIntent);
		isSomeChanges = false;
		sProduct = productName.getText().toString();
		sStore = storeName.getText().toString();
		sComment = comments.getText().toString();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if ((keyCode == KeyEvent.KEYCODE_BACK)) {
			Log.d(this.getClass().getName(), "" + isSomeChanges);

			if (!productName.getText().toString().equals(sProduct) || !storeName.getText().toString().equals(sStore)
					|| !comments.getText().toString().equals(sComment))
				isSomeChanges = true;
			if (isSomeChanges) {
				showDialog(CLOSE_ACTIVITY);
			}
		}
		// return false;//super.onKeyDown(keyCode, event);
		return super.onKeyDown(keyCode, event);
	}

	public void getImageToUpload(View view) {
		if (advancedPopup) {
			// TODO
			if (content_type != null && content_type.equals(APPLICATION_PDF)) {
				String path_to_pdf = (String) imageToUpload.getTag();
				if (path_to_pdf != null) {
					Log.e("path_to_pdf", path_to_pdf);
					File file = new File(path_to_pdf);
					if (file.exists()) {
						Uri path = Uri.fromFile(file);
						Intent intent = new Intent(Intent.ACTION_VIEW);
						intent.setDataAndType(path, "application/pdf");
						intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

						try {
							startActivity(intent);
						} catch (ActivityNotFoundException e) {
							ToastUtil.showText(UploadActivity.this, getString(R.string.download_that_app));
							Intent intentPDF = new Intent(Intent.ACTION_VIEW);
							intentPDF.setData(Uri.parse("market://search?q=pname:com.adobe.reader"));
							try {
								startActivity(intentPDF);
							} catch (Exception e2) {
								e2.printStackTrace();
							}

						}
					}
				}

			} else {
				Bitmap bm = BitmapFactory.decodeFile((String) imageToUpload.getTag(), getBitmapOptions(1));
				new TakeImageDialogWithImage(this, bm, new Runnable() {
					@Override
					public void run() {
						// take new photo
						if (isSDPresent()) {
							String fileName = "temp.jpeg";
							ContentValues values = new ContentValues();
							values.put(MediaStore.Images.Media.TITLE, fileName);
							mCapturedImageURI = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
							// Log.e("asd", "" + mCapturedImageURI);
							MyPreferences.setUri(UploadActivity.this, mCapturedImageURI.toString());
							Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
							intent.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI);
							setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
							startActivityForResult(intent, SELECT_PHOTO);
						} else {
							ToastUtil.showText(getApplicationContext(), getString(R.string.no_sdcard));
						}

					}
				}, new Runnable() {
					@Override
					public void run() {
						// use current image from Android gallery
						final Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI);
						intent.setType("image/*");
						startActivityForResult(intent, IMAGE_PICKER_REQUEST);
					}
				}).show();
			}

		} else {
			new TakeImageDialog(this, new Runnable() {
				@Override
				public void run() {
					// take new photo
					if (isSDPresent()) {
						String fileName = "temp.jpeg";
						ContentValues values = new ContentValues();
						values.put(MediaStore.Images.Media.TITLE, fileName);
						mCapturedImageURI = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
						MyPreferences.setUri(UploadActivity.this, mCapturedImageURI.toString());
						Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
						intent.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI);
						setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
						startActivityForResult(intent, SELECT_PHOTO);
					} else {
						ToastUtil.showText(getApplicationContext(), getString(R.string.no_sdcard));
					}

				}
			}, new Runnable() {
				@Override
				public void run() {
					// use current image from Android gallery
					final Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI);
					intent.setType("image/*");
					startActivityForResult(intent, IMAGE_PICKER_REQUEST);
				}
			}).show();
		}
	}

	private boolean isSDPresent() {
		return android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
		super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
		isSomeChanges = true;

		if (imageBitmap != null)
			imageBitmap.recycle();
		// TODO
		switch (requestCode) {
		case SELECT_PHOTO:
			if (resultCode == RESULT_OK) {
				isImageUpload = true;
				Uri uri = Uri.parse(MyPreferences.getUri(UploadActivity.this));
				if (uri != null) {
					uriGallery = uri.toString();
					setLogoFromGallery(uri, imageToUpload);
				}
			}
			break;
		case IMAGE_PICKER_REQUEST:
			if (resultCode == RESULT_OK) {
				isImageUpload = true;
				Uri selectedImage = imageReturnedIntent.getData();
				uriGallery = selectedImage.toString();
				setLogoFromGallery(selectedImage, imageToUpload);
			}
			break;
		case (PICK_CONTACT):
			if (resultCode == Activity.RESULT_OK) {
				Uri contactData = imageReturnedIntent.getData();
				Cursor c = managedQuery(contactData, null, null, null, null);
				if (c.moveToFirst()) {
					String id = c.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts._ID));
					c = managedQuery(Email.CONTENT_URI, null, Email.CONTACT_ID + "=?", new String[] { id }, null);
					if (c.moveToFirst()) {
						String email = c.getString(c.getColumnIndex(Email.DATA1));
						edtTranferEmail.setText(email);
					}
				}
				break;
			}
			break;
		}
	}

	private void setLogoFromGallery(Uri uri, ImageView imageView) {
		String[] projection = { MediaStore.Images.Media.DATA };
		Cursor cursor = managedQuery(uri, projection, null, null, null);
		int column_index_data = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
		cursor.moveToFirst();
		String capturedImageFilePath = cursor.getString(column_index_data);
		cursor.close();

		InputStream imageStream = null;
		try {
			imageStream = getContentResolver().openInputStream(uri);
			Bitmap yourSelectedImage = BitmapFactory.decodeStream(imageStream, null, getBitmapOptions(6));
			ExifInterface exifInterface = new ExifInterface(capturedImageFilePath);
			int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, 1);
			switch (orientation) {
			// horizontal on Samsung Galaxy S2
			case 6:
				Matrix mtx = new Matrix();
				mtx.postRotate(90);
				// Rotating Bitmap
				yourSelectedImage = Bitmap.createBitmap(yourSelectedImage, 0, 0, yourSelectedImage.getWidth(), yourSelectedImage.getHeight(), mtx, true);
				break;
			default:
				break;
			}

			imageView.setImageBitmap(yourSelectedImage);
		} catch (Exception e) {
			e.printStackTrace();
			imageView.setImageResource(R.drawable.icon_warranty);
		}

	}

	private BitmapFactory.Options getBitmapOptions(int scale) {
		if (_bitmapOptions == null) {
			_bitmapOptions = new BitmapFactory.Options();
			// _bitmapOptions.inTempStorage = new byte[256];
			_bitmapOptions.inPreferredConfig = Bitmap.Config.RGB_565;
			_bitmapOptions.inJustDecodeBounds = false; // this will request the
														// bm
			_bitmapOptions.inSampleSize = scale; // scaled down by 4
		}
		return _bitmapOptions;
	}

	public Bitmap scaleBitmap(Bitmap bitmap) {
		int newWidth = 6 * 240;
		int newHeight = 6 * 160;
		int origWidth = bitmap.getWidth();
		int origHeight = bitmap.getHeight();

		// If no new width or height were specified return the original bitmap
		if (newWidth <= 0 && newHeight <= 0) {
			return bitmap;
		}
		// Only the width was specified
		else if (newWidth > 0 && newHeight <= 0) {
			newHeight = (newWidth * origHeight) / origWidth;
		}
		// only the height was specified
		else if (newWidth <= 0 && newHeight > 0) {
			newWidth = (newHeight * origWidth) / origHeight;
		} else {
			double newRatio = newWidth / (double) newHeight;
			double origRatio = origWidth / (double) origHeight;

			if (origRatio > newRatio) {
				newHeight = (newWidth * origHeight) / origWidth;
			} else if (origRatio < newRatio) {
				newWidth = (newHeight * origWidth) / origHeight;
			}
		}

		return Bitmap.createScaledBitmap(bitmap, newWidth, newHeight, true);
	}

	public void onSetDatePurchase(View view) {
		showDialog(DATE_DIALOG_ID_PURCHASE);
	}

	public void onSetDateExpire(View view) {
		showDialog(DATE_DIALOG_ID_EXPIRE);
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);

		switch (id) {
		case DATE_DIALOG_ID_PURCHASE:
			return new DatePickerDialog(this, mDateSetListenerPurchase, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH),
					calendar.get(Calendar.DAY_OF_MONTH));
		case DATE_DIALOG_ID_EXPIRE:
			return new DatePickerDialog(this, mDateSetListenerExpire, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH),
					calendar.get(Calendar.DAY_OF_MONTH));
		case CONFIRM:
			builder.setMessage(R.string.cost_one_upload);
			builder.setPositiveButton(getString(R.string.ok), new OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					doUpload();
				}
			});
			builder.setNegativeButton(getString(R.string.cancel), new OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {

				}
			});

			builder.setCancelable(true);
			return builder.create();
		case CLOSE_ACTIVITY:
			builder.setTitle(getString(R.string.your_changes));
			builder.setPositiveButton(getString(R.string.ok), new OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					finish();
				}
			});
			builder.setNegativeButton(getString(R.string.cancel), new OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {

				}
			});

			builder.setCancelable(true);
			return builder.create();

		}
		return null;
	}

	public void showProductEditBox(final View view, String title) {
		final AlertDialog.Builder alert = new AlertDialog.Builder(this);
		alert.setTitle(title);
		final EditText input = new EditText(this);
		alert.setView(input);
		alert.setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				String value = input.getText().toString().trim();

				TextView txtValueItem = (TextView) view.findViewById(R.id.item_value_upload);
				txtValueItem.setText(value);
			}
		});

		alert.setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				dialog.cancel();
			}
		});
		alert.show();
	}

	// the callback received when the user "sets" the date in the dialog
	private DatePickerDialog.OnDateSetListener mDateSetListenerPurchase = new DatePickerDialog.OnDateSetListener() {
		public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
			calendar.set(Calendar.YEAR, year);
			calendar.set(Calendar.MONTH, monthOfYear);
			calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
			purchaseDate.setText(DateFormat.format(Keys.dateFormat, calendar));
			purchaseDate.setTag(calendar.getTimeInMillis());
			isSomeChanges = true;
		}
	};

	private DatePickerDialog.OnDateSetListener mDateSetListenerExpire = new DatePickerDialog.OnDateSetListener() {
		public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
			calendar.set(Calendar.YEAR, year);
			calendar.set(Calendar.MONTH, monthOfYear);
			calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
			expiryDate.setText(DateFormat.format(Keys.dateFormat, calendar));
			expiryDate.setTag(calendar.getTimeInMillis());
			isSomeChanges = true;
		}
	};

	@Override
	public void onReceiveResult(int resultCode, Bundle resultData) {
		switch (resultCode) {
		case UpdateIntentService.STATUS_RUNNING:
			// do nothing
			break;
		case UpdateIntentService.STATUS_ERROR:
			if (null != progress)
				progress.dismiss();
			// ToastUtil.showText(getApplicationContext(),
			// resultData.getString(UpdateIntentService.ERROR_MESSAGE));
			break;

		case UpdateIntentService.STATUS_FINISHED:
			if (null != progress)
				progress.dismiss();

			if (resultData.containsKey(Keys.actionIdentificator) && resultData.getInt(Keys.actionIdentificator) == QueriesCodes.ACCOUNT_UPLOAD_BY_ID) {
				finish();
			} else if (resultData.containsKey(Keys.isTransfer) && resultData.getBoolean(Keys.isTransfer)) {
				String result = getString(R.string.tranfer_succ);
				ToastUtil.showText(getApplicationContext(), result);
			} else {
				String result;
				result = (resultData.containsKey(Keys._isUploadWarranty) && resultData.getBoolean(Keys._isUploadWarranty)) ? getString(R.string.warranty_upload_success)
						: getString(R.string.warranty_does_not_upload);
				ToastUtil.showText(getApplicationContext(), result);
				isSomeChanges = false;
				if (result.equals(getString(R.string.warranty_upload_success))) {
					// update local db
					if (resultData.containsKey(Keys._isUploadWarranty) && resultData.getBoolean(Keys._isUploadWarranty) && null != accountUploadID) {
						Intent updateIntent = new Intent(Intent.ACTION_SYNC, null, this, UpdateIntentService.class);
						updateIntent.putExtra(UpdateIntentService.EXTRA_STATUS_RECEIVER, receiver);
						updateIntent.putExtra(Keys._account_upload_id, accountUploadID);
						updateIntent.putExtra(UpdateIntentService.EXTRA_REQUEST_CODE, QueriesCodes.ACCOUNT_UPLOAD_BY_ID);
						startService(updateIntent);
					}
					needClaerCasce = true;
					finish();
				}

			}
			break;
		}
	}

	// private void doTransferEmail(String email) {
	// Intent updateIntent = new Intent(Intent.ACTION_SYNC, null, this,
	// UpdateIntentService.class);
	// updateIntent.putExtra(UpdateIntentService.EXTRA_STATUS_RECEIVER,
	// receiver);
	// updateIntent.putExtra(Keys._account_upload_id, uploadId);
	// updateIntent.putExtra(Keys._transferTargetEmail, email);
	// updateIntent.putExtra(UpdateIntentService.EXTRA_REQUEST_CODE,
	// QueriesCodes.ACCOUNT_UPLOAD_TRANSFER);
	// startService(updateIntent);
	// }

}
